import request from "/utils/omsRequest";
import validator from "/utils/validators";
import { showToast } from "/utils/common";
import { contractType } from "/utils/dictionary";
import { bus } from "/utils/core";
const contractTypes = [];
for (const i in contractType) {
  contractTypes.push({
    value: i,
    label: contractType[i]
  })
}

Page({
  data: {
    products: [],
    productMap: {},
    services: [],
    orgList: [],
    dingUserList: [],
    dingOrgIndex: null,
    dingUserIndex: null,
    contractTypeIndex: null,
    contractTypes,
    form: {
      depositList: []
    }
  },
  onUnload() {
    bus.remove("contractFile")
  },
  async onLoad(query) {
    bus.subscribe("contractFile", (files) => {
      if (files.length > 0) {
        this.data.form.sysEnclosureList.push(...files);
        this.setData({
          form: this.data.form
        });
      }
    })
    request({
      url: "/ajax/product/list"
    }).then(res => {
      let productMap = {};
      res.voList.forEach(product => {
        productMap[product.id] = product.name
      });
      this.setData({
        products: res.voList,
        productMap: productMap
      });
    });
    request({
      url: "/ajax/freeService/list"
    }).then(res => {
      this.setData({
        services: res.voList
      });
    });
    await request({
      url: "/ajax/user/org",
      data: {
        departmentId: 113682313
      }
    }).then(res => {
      this.setData({
        orgList: res.voList
      })
    });
    await request({
      url: "/ajax/contract/findContract",
      data: {
        id: query.id
      }
    }).then(res => {
      res.vo.saleDingOrgId = +res.vo.saleDingOrgId;
      res.vo.contractList.map(item => {
        item.startDate = item.startDate.replace('T', ' ').substr(0, 10);
        item.endDate = item.endDate.replace('T', ' ').substr(0, 10);
      });
      const contractTypeIndex = this.data.contractTypes.findIndex(item => item.value === res.vo.contractType);
      res.vo.depositList = []
      res.vo.contractList.forEach(product => {
        if (product.contractDepositRecordList) {
          product.contractDepositRecordList.map(item => {
            item.productId = product.productId;
            item.depositDate = item.depositDate.replace("T", " ").substr(0, 10)
          });
          res.vo.depositList.push(...product.contractDepositRecordList)
        }
      });
      this.setData({
        form: res.vo,
        dingOrgIndex: this.data.orgList.findIndex(item => item.id === res.vo.saleDingOrgId),
        contractTypeIndex: contractTypeIndex >= 0 ? contractTypeIndex : null
      })
    });
    request({
      url: "/ajax/user/dingUser",
      data: {
        departmentId: this.data.form.saleDingOrgId
      }
    }).then(res => {
      this.setData({
        dingUserList: res.voList,
        dingUserIndex: res.voList.findIndex(item => item.userid === this.data.form.saleDingUserId)
      });
    })
    request({
      url: "/ajax/contractFreeService/list",
      data: {
        contractGroupId: query.id
      }
    }).then(res => {
      this.setData({
        "form.freeServiceList": res.voList.filter(item => item.freeServiceType === "FREE"),
        "form.buyServiceList": res.voList.filter(item => item.freeServiceType === "BUY")
      })
    })
  },
  // 合同类型change
  onContractTypeChange(e) {
    this.setData({
      contractTypeIndex: e.detail.value,
      "form.contractType": this.data.contractTypes[e.detail.value].value
    })
  },
  // 产品增删改 (同步收款记录)
  onProductChange(obj) {
    if (obj.index === null && obj.form) {
      // new 
      if (obj.form.productId === 22) {
        this.setData({
          "form.buyServiceList": obj.buyServiceList
        })
      }
      this.data.form.contractList.push(obj.form);
    }
    if (obj.index !== null && obj.form) {
      // update
      if (obj.form.productId === 22) {
        this.setData({
          "form.buyServiceList": obj.buyServiceList
        })
      }
      this.data.form.contractList.splice(obj.index, 1, obj.form);
      this.syncDepositList()
    }
    if (obj.index !== null && !obj.form) {
      // remove
      if (this.data.form.contractList[obj.index].productId === 22) {
        this.setData({
          "form.buyServiceList": []
        })
      }
      this.data.form.contractList.splice(obj.index, 1);
      this.syncDepositList()
    }
    this.setData({
      "form.contractList": this.data.form.contractList
    });
  },
  // 赠送增值服务增删改
  onServiceChange(obj) {
    if (obj.index === null && obj.form) {
      this.data.form.freeServiceList.push(obj.form);
    } else if (obj.index !== null && obj.form) {
      this.data.form.freeServiceList.splice(obj.index, 1, obj.form);
    } else if (obj.index !== null && !obj.form) {
      this.data.form.freeServiceList.splice(obj.index, 1);
    }
    this.setData({
      "form.freeServiceList": this.data.form.freeServiceList
    });
  },
  // 购买增值服务增删改
  onBuyServiceChange(obj) {
    if (obj.index === null && obj.form) {
      this.data.form.buyServiceList.push(obj.form)
    } else if (obj.index !== null && obj.form) {
      this.data.form.buyServiceList.splice(obj.index, 1, obj.form)
    } else if (obj.index !== null && !obj.form) {
      this.data.form.buyServiceList.splice(obj.index, 1)
    }
    this.setData({
      "form.buyServiceList": this.data.form.buyServiceList
    })
  },
  // 收款记录增删改
  onDepositChange(obj) {
    if (obj.index === null && obj.form) {
      this.data.form.depositList.push(obj.form)
    } else if (obj.index !== null && obj.form) {
      this.data.form.depositList.splice(obj.index, 1, obj.form)
    } else if (obj.index !== null && !obj.form) {
      this.data.form.depositList.splice(obj.index, 1)
    }
    this.setData({
      "form.depositList": this.data.form.depositList
    })
  },
  // 同步收款记录
  syncDepositList() {
    for (let i = 0; i < this.data.form.depositList.length; i++) {
      let filteredData = this.data.form.contractList.find(item => item.productId === this.data.form.depositList[i].productId);
      if (!filteredData) {
        this.data.form.depositList.splice(i, 1);
        i--;
      }
    }
    this.setData({
      "form.depositList": this.data.form.depositList
    })
  },
  onDingOrgChange(e) {
    this.setData({
      dingOrgIndex: this.data.orgList.length > 0 ? e.detail.value : null,
      "form.saleDingOrgId": this.data.orgList.length > 0 ? this.data.orgList[e.detail.value].id : null,
      dingUserIndex: null,
      "form.saleDingUserId": null
    })
    request({
      url: "/ajax/user/dingUser",
      data: {
        departmentId: this.data.orgList[e.detail.value].id
      }
    }).then(res => {
      this.setData({
        dingUserList: res.voList
      })
    })
  },
  // 删除合同附件
  onRemoveFile(e) {
    this.data.form.sysEnclosureList.splice(e.target.dataset.index, 1);
    this.setData({
      form: this.data.form
    });
  },
  onSubmit() {
    let validate = new validator();
    validate.add("checkEmpty", this.data.form.contractType, "请选择合同类型");
    validate.add("checkEmptyArray", this.data.form.contractList, "请至少添加一个产品");
    if (this.data.form.contractList.find(item => item.productId === 22)) {
      validate.add("checkEmptyArray", this.data.form.buyServiceList, "增值服务合同，至少添加一条购买增值服务")
    }
    validate.add("checkEmpty", this.data.form.saleDingOrgId, "请选择所属机构");
    validate.add("checkEmpty", this.data.form.saleDingUserId, "请选择所属销售");
    validate.add("checkEmptyArray", this.data.form.depositList, "请上传收款记录");
    validate.add("checkEmptyArray", this.data.form.sysEnclosureList, "请至少添加一个合同附件");
    if (validate.check()) {
      this.data.form.freeServiceAmount = this.data.form.freeServiceList.reduce((pre, cur) => pre + cur.totalPrice, 0);
      let data = JSON.parse(JSON.stringify(this.data.form))
      data.freeServiceList.push(...data.buyServiceList);
      data.contractList.forEach(contract => {
        contract.contractDepositRecordList = data.depositList.filter(
          item => item.productId === contract.productId
        );
      });
      console.log(data)
      dd.showLoading({
        content: '加载中...'
      });
      request({
        url: "/ajax/contract/updateContract",
        method: "post",
        data: data,
        headers: {
          "Content-Type": "application/json;utf-8"
        }
      }).then(() => {
        dd.hideLoading();
        showToast({
          type: "success",
          msg: "修改成功!"
        });
        dd.navigateBack();
      })
    }
  }
});
